<?php

class Arsip extends Controller {

	function Arsip() {
		parent::Controller();
        $this->load->model('Arsip_model', 'p');
	}
	
	function index() {
		if (!$this->session->userdata('username')) {
			$data['isLogin'] = FALSE;
        	redirect("/login", "location");
		} else {
			$data['isLogin'] = TRUE;
			$data['username'] = $this->session->userdata('username');
			$data['role'] = $this->session->userdata('role');
		}

        $tabel_header = $this->p->list_header();
        $nama_variabel = 'data';
        $isi = 'var '.$nama_variabel.'='.$this->p->list_isi();
        
		$data['additional_js'] = '
		<script type="text/javascript">
		function deleteRow(id) {
			var txt = \'Anda yakin mau menghapus data arsip ini?<input type="hidden" id="row-id" name="row-id" value="\'+ id +\'" />\';
				url = "'.base_url().'index_arsip.php/arsip/hapus/"+id;
			 $.ajax({
			   type: "POST",
               data:"a=1",
			   url: "'.base_url().'index_arsip.php/arsip/bisa_dihapus/"+id,
			   success: function(msg) {
				 if (msg==\'bisa\') {
					$.prompt(txt,{
						buttons:{Hapus:true, Batal:false},
						callback: function(v){
							if(v) {
								$("tr#row-"+id).fadeOut("slow", function() {
									$("tr#row-"+id).remove();
								});
								top.location.href=url;
							}
						}
					});
				 } else {
					$.prompt(\'Maaf, data arsip tidak dapat dihapus dikarenakan terkait dengan data lain.\');
				 }
		       }
		    });
		}
		</script>
        <script type="text/javascript">
            '.$isi.'

            // This file demonstrates the different options of the pagination plugin
            // It also demonstrates how to use a JavaScript data structure to
            // generate the paginated content and how to display more than one
            // item per page with items_per_page.

            /**
             * Callback function that displays the content.
             *
             * Gets called every time the user clicks on a pagination link.
             *
             * @param {int}page_index New Page index
             * @param {jQuery} jq the container with the pagination links as a jQuery object
             */
			function pageselectCallback(page_index, jq){
                // Get number of elements per pagionation page from form
                var items_per_page = '.ROW_PER_PAGE.';
                var max_elem = Math.min((page_index+1) * items_per_page, '.$nama_variabel.'.length);
                var newcontent = \''.$tabel_header.'\';

                // Iterate through a selection of the content and build an HTML string
                for(var i=page_index*items_per_page;i<max_elem;i++)
                {
                    newcontent += '.$nama_variabel.'[i];
                }

                newcontent += \'</tbody></table>\';

                // Replace old content with new content
                $("#isi_tabel").html(newcontent);

                //$("#scrollable").tablesorter({sortList: [[1,0]], headers: { 0:{sorter: false}, 2:{sorter: false}, 8:{sorter: false}, 11:{sorter: false} }, widthFixed: true, widgets: [\'zebra\']});

                // Prevent click eventpropagation
                return false;
            }

            // When document has loaded, initialize pagination and form
            $(document).ready(function(){
                $("#paginasi").pagination('.$nama_variabel.'.length, {
                    items_per_page:'.ROW_PER_PAGE.',
                    num_edge_entries: '.NUM_EDGE_ENTRIES.',
                    next_text: \''.TEKS_NEXT.'\',
                    prev_text: \''.TEKS_PREV.'\',
                    next_show_always: '.ALWAYS_SHOW_NEXT.',
                    prev_show_always: '.ALWAYS_SHOW_PREV.',
                    callback:pageselectCallback
                });
            });

        </script>
		';
		
		$data['judul'] = 'Arsip';
        $data['tampilkan_menu'] = true;
        $data['link_tambah'] = base_url().'index_arsip.php/arsip/form_isian/';
        $data['teks_link_tambah'] = 'Arsip Baru';
        $data['filter'] = '';//Filter: '.combo_kategori_arsip('kategori', '');
        
        $this->load->view('view_main',$data);
    }

    function _setRules($is_baru=true) {
    	return '
                    //set the rules for the field names
                    rules: {
                        judul: { required: true },
                        pta_id_kategori_arsip: { required: true },'.
                        ($is_baru?'namafile: { required: true },':'').
                       'tgl_dokumen: { required: true },
                        kode_viewer: { required: true }
                    },
                    //set messages to appear inline
                    messages: {
                        judul: "Judul Arsip wajib diisi",
                        pta_id_kategori_arsip: "Kategori wajib diisi",'.
                        ($is_baru?'namafile: "Nama File wajib diisi",':'').
                       'tgl_dokumen: "Tanggal Dokumen wajib diisi",
                        kode_viewer: "Viewer wajib diisi"
    				}
    	';
    }
    
    function _setJsForm($additional_string,$is_baru=true) {
    	$ret = '
		<script type="text/javascript">
        	$(function() {
        		$("#div_viewer").hide();
		        $("#judul").focus();
//            	$(\'.date-pick\').datePicker({startDate:\'11/11/1981\'});
		        $("#btn_kembali").click( function() {
                    window.location = \''.base_url().'index_arsip.php/arsip\';
                });
                // validate contact form on keyup and submit
                $("form").validate({
                    '.$this->_setRules($is_baru).'
                });
                $("#kode_viewer").change(function(){
                	var kode = $("#kode_viewer").val();
                	if (kode == 1) {
                		$("#div_viewer").show("slow");
                	} 
                });
        	});
        </script>
    	';
    	return $ret;
    }
    
    function _setCSS() {
    	return '
			<style type="text/css">
            a.dp-choose-date {
                float: left;
                width: 16px;
                height: 16px;
                padding: 0;
                margin: 5px 3px 0;
                display: block;
                text-indent: -2000px;
                overflow: hidden;
                background: url('.base_url().'templates/images/cal.gif) no-repeat;
            }
            a.dp-choose-date.dp-disabled {
                background-position: 0 -20px;
                cursor: default;
            }
            /* makes the input field shorter once the date picker code
             * has run (to allow space for the calendar icon
             */
            input.dp-applied {
                width: 140px;
                float: left;
            }
            </style>
    	';
    }
    
    function form_isian() {
		if (!$this->session->userdata('username')) {
			$data['isLogin'] = FALSE;
        	redirect("/login", "location");
		} else {
			$data['isLogin'] = TRUE;
			$data['username'] = $this->session->userdata('username');
			$data['role'] = $this->session->userdata('role');
		}
		
        $form_action = base_url().'index_arsip.php/arsip/simpan';
        $form_id = 'form_arsip';
        
        $data['additional_js'] = $this->_setJsForm("");
        $data['additional_css'] = $this->_setCSS();
        
        $data['judul'] = 'Arsip Baru';
        $data['list_data'] = $this->p->entry_form($form_id,$form_action);
        $this->load->view('view_farsip', $data);
    }
    
    function simpan($is_update=FALSE, $id='') {
        if (!$this->input->post('judul')) {
            redirect('arsip', 'refresh');
        } else {
        	$arr['judul'] = $this->input->post('judul');
        }

        $arr['pta_id_kategori_arsip'] = $this->input->post('pta_id_kategori_arsip')?$this->input->post('pta_id_kategori_arsip'):"0";
        $arr['published'] = $this->input->post('published')?$this->input->post('published'):"";
        $arr['jenis'] = 1;//$this->input->post('jenis')?$this->input->post('jenis'):"1";
        $arr['deskripsi'] = $this->input->post('deskripsi')?$this->input->post('deskripsi'):"";
        $arr['tgl_dokumen'] = $this->input->post('tgl_dokumen')?DMY2YMD(str_replace("/", TGL_SEPARATOR, $this->input->post('tgl_dokumen')), TGL_SEPARATOR):date('Y-m-d');
        $arr['kode_viewer'] = $this->input->post('kode_viewer')?$this->input->post('kode_viewer'):VIEWER_EVERYBODY;
        if ($arr['kode_viewer']!=VIEWER_EVERYBODY) {
        	$arr['viewer'] = $this->input->post('viewer')?$this->input->post('viewer'):"";
        }
        
        if ($is_update) {
        	if ($_FILES['namafile']['name'] != "") {
				/* sebelum update file, rename dulu file lama
				 * format file lama: <id_file><YYYYmmddHHmmss><nama_file>
				 */
		        $this->load->model('Datum_model', 'd');
		
				$id_file = $this->d->getData('pta_id_files', 'arsip', array('idpta_arsip'=>$id));
				$nama_file = $this->d->getData('namafile', 'files', array('idpta_files' => $id_file));
				if (file_exists(BASE_UPLOAD_ARSIP.$id_file.$nama_file)) {
					rename( BASE_UPLOAD_ARSIP.$id_file.$nama_file, BASE_UPLOAD_ARSIP.$id_file.date('YmdHis').$nama_file);
				}
        	}
        }
        
        if ($_FILES['namafile']['name'] != "") {
	        $config['upload_path'] = BASE_UPLOAD_ARSIP;
			$config['allowed_types'] = UPLOAD_ALLOWED_FILETYPE;
			$config['max_size']	= UPLOAD_SIZE_MAKSIMUM;
			
			$this->load->library('upload', $config);
			if ( $this->upload->do_upload('namafile') ) {
				$data_uplot = $this->upload->data();
	        	
				$arr_file['namafile'] = $data_uplot['file_name'];
				$arr_file['ukuran'] = $data_uplot['file_size'];
				$arr_file['ekstensi'] = $data_uplot['file_ext'];
				$arr_file['tipe_file'] = $data_uplot['file_type'];
				$arr_file['pta_user_namauser'] = $this->session->userdata('username'); 
				if ($is_update) {
					$this->db->where(array('idpta_files' => $id_file));
					$this->db->update('files', $arr_file);
				} else {
					$this->db->insert('files', $arr_file);
					$arr['pta_id_files'] = $this->db->insert_id();
					$id_file = $arr['pta_id_files'];
				}

				/* rename file di server
				 * format file : <id_file><nama_file>
				 */
				rename( BASE_UPLOAD_ARSIP.$arr_file['namafile'], BASE_UPLOAD_ARSIP.$id_file.$arr_file['namafile']);
			} else {
				die($this->upload->display_errors());
			}
        }

		$arr['user_update'] = $this->session->userdata('username'); 
		if ($is_update) {
			$this->p->simpan($arr, $is_update, $id);
        } else {
			$arr['user_input'] = $this->session->userdata('username'); 
			$arr['tgl_input'] = date('Y-m-d H:i:s'); 
			$this->p->simpan($arr);
        }

        redirect('arsip', 'refresh');
    }
    
    function form_edit($id) {
		if (!$this->session->userdata('username')) {
			$data['isLogin'] = FALSE;
        	redirect("/login", "location");
		} else {
			$data['isLogin'] = TRUE;
			$data['username'] = $this->session->userdata('username');
			$data['role'] = $this->session->userdata('role');
		}
		
        $data['additional_js'] = $this->_setJsForm("",false);
        $data['additional_css'] = $this->_setCSS();
        
        $this->db->where(array('idpta_arsip' => $id));
        $q = $this->db->get('arsip');
        if ($q->num_rows() > 0) {
            $row = $q->row();
            $arr['judul']                  = $row->judul;
            $arr['pta_id_kategori_arsip']  = $row->pta_id_kategori_arsip;
            $arr['published']              = $row->published;
            $arr['jenis']                  = $row->jenis;
            $arr['deskripsi']              = $row->deskripsi;
            $arr['tgl_dokumen']            = YMD2DMY(trimTime($row->tgl_dokumen), TGL_SEPARATOR);
            $arr['kode_viewer']            = $row->kode_viewer;
            $arr['viewer']                 = $row->viewer;
            
            $this->load->model('Datum_model', 'd');
            $arr['namafile']               = $this->d->getData('namafile', 'files', array('idpta_files' => $row->pta_id_files));
            
            $arr['created_by']             = sprintf('%s pada %s', $row->user_input, YMD2Indo(trimTime($row->tgl_input), TGL_SEPARATOR));
            if ($row->user_update!='') {
            	$arr['last_update']        = sprintf('%s pada %s', $row->user_update, YMD2Indo(trimTime($row->tgl_update), TGL_SEPARATOR));
            }
            
	    	$form_action = base_url().'index_arsip.php/arsip/simpan/true/'.$id;
	        $form_id = 'form_arsip';

            $data['judul'] = 'Ubah Arsip';
            $data['list_data'] = $this->p->entry_form($form_id,$form_action,$arr);
            $this->load->view('view_farsip', $data);
        } else {
            redirect('arsip', 'refresh');
        }
    }


    function hapus($id) {
    	$this->load->model('Datum_model', 'd');
    	$id_file = $this->d->getData('pta_id_files', 'arsip', array('idpta_arsip'=>$id));
    	
        $this->db->where('idpta_arsip', $id);
        $this->db->delete('arsip');
        if ($this->db->affected_rows()>0) {
	        $namafile = $this->d->getData('namafile', 'files', array('idpta_files'=>$id_file));
	        rename( BASE_UPLOAD_ARSIP.$id_file.$namafile, BASE_UPLOAD_ARSIP.'_del'.date('YmdHis').$id_file.$namafile );
	        
        	$this->db->where('idpta_files', $id_file);
	        $this->db->delete('files');
        }
        redirect('arsip', 'refresh');
    }
    
    
    function bisa_dihapus($id) {
    	echo 'bisa';
    }
    
    function show_detil($id) {

    echo Arsip_model::arsip_detil($id);

    }
    
    function unduh_arsip($id) {
    /*  if (!$this->session->userdata('username')) {
            $data['isLogin'] = FALSE;
            redirect("/login", "location");
        } else {
            $data['isLogin'] = TRUE;
            $data['username'] = $this->session->userdata('username');
            $data['role'] = $this->session->userdata('role');
        }
    */
    $this->db->where("idpta_arsip = $id" );      
    $q = $this->db->get('arsip');
    
    $this->load->model('Datum_model'); 
    foreach($q->result() as $row) {   
      $namafile = Datum_model::getData('namafile', 'files', array('idpta_files' => $row->pta_id_files));      
      $no = $row->pta_id_files;
      $Count = $row->hits;
      $FileURL = base_url().substr(BASE_UPLOAD_ARSIP,2).$no.$namafile;
      
      header('Location: '.$FileURL);
      
      $arr = Array('hits' => $Count+1);
      $this->db->where('idpta_arsip', $id);
      $this->db->update('arsip', $arr);
    }
    
    /* $this->load->model('Datum_model', 'd');
        $id_file = $this->d->getData('pta_id_files', 'arsip', array('idpta_arsip'=>$id));
        $namafile = $this->d->getData('namafile', 'files', array('idpta_files'=>$id_file));
        
        $data['judul'] = $this->d->getData('judul', 'arsip', array('idpta_arsip'=>$id));
        $data['isi'] = '<center><p><img src="'.base_url().'uploads/arsip/'.$id_file.$namafile.'" /><p></center>';
        $data['link_kembali'] = 'javascript:window.close();';
        $this->load->view('view_blank', $data);
       redirect("../uploads/".$namafile, "location");     */
  }
    
}

/* End of file arsip.php */
/* Location: ./system/application/arsip/controllers/arsip.php */